import { ref, computed, onMounted } from "vue";
import { message } from "@/utils/message";
import {
  createCtpSettings,
  updateCtpSettings,
  getAllCtpSettings,
  type CtpSettings
} from "@/api/settings";
import { isTouchDevice, useBreakpointQuery } from "@/utils/device";
import type { PlusColumn, PlusDialogProps } from "plus-pro-components";

type DialogMode = "new" | "edit" | "copy";

const emptyModel = (): CtpSettings => ({
  name: "",
  name_cn: "",
  user_id: "",
  password: "",
  broker_id: "",
  td_address: "",
  md_address: "",
  app_id: "",
  auth_code: "",
  broker_name_cn: ""
});

export function useCtpSettingsPage() {
  const { isMdUp } = useBreakpointQuery();

  // table state
  const tableData = ref<CtpSettings[]>([]);
  const searchQuery = ref("");
  const currentRow = ref<CtpSettings | null>(null);

  const tableSize = computed(() => (isMdUp() ? "default" : "small"));

  const tableColumns: TableColumnList = [
    {
      label: "配置id",
      prop: "name",
      sortable: true,
      minWidth: 120,
      showOverflowTooltip: true
    },
    {
      label: "配置名称",
      prop: "name_cn",
      sortable: true,
      minWidth: 120,
      showOverflowTooltip: true
    },
    {
      label: "用户ID",
      prop: "user_id",
      minWidth: 120,
      showOverflowTooltip: true
    },
    {
      label: "期货公司",
      prop: "broker_name_cn",
      minWidth: 120,
      showOverflowTooltip: true
    },
    {
      label: "BrokerID",
      prop: "broker_id",
      minWidth: 120,
      showOverflowTooltip: true
    }
  ];

  const filteredData = computed(() => {
    const q = (searchQuery.value || "").toLowerCase();
    if (!q) return tableData.value;
    return tableData.value.filter(row =>
      (row.name || "").toLowerCase().includes(q)
    );
  });

  const isRowSelected = computed(() => !!currentRow.value);

  const onCurrentChange = (row: CtpSettings | null) => {
    currentRow.value = row;
  };

  const onRowClick = (row: CtpSettings) => {
    if (!isTouchDevice()) return;
    onCurrentChange(row);
    openEdit();
  };

  // form/dialog state
  const dialogVisible = ref(false);
  const dialogMode = ref<DialogMode>("new");
  const dialogTitle = computed(() => {
    switch (dialogMode.value) {
      case "edit":
        return "编辑配置";
      case "copy":
        return "复制配置";
      default:
        return "新建配置";
    }
  });

  const dialogWidth = computed(() => (isMdUp() ? "720px" : "95vw"));

  const dialogProps = computed<PlusDialogProps>(() => ({
    title: dialogTitle.value,
    width: dialogWidth.value,
    closeOnClickModal: false,
    destroyOnClose: true
  }));

  const formRules = ref<Partial<Record<string, any[]>>>({
    name: [{ required: true, message: "请输入配置名称", trigger: "blur" }],
    user_id: [{ required: true, message: "请输入用户ID", trigger: "blur" }],
    password: [{ required: true, message: "请输入密码", trigger: "blur" }],
    broker_id: [{ required: true, message: "请输入BrokerID", trigger: "blur" }],
    td_address: [
      { required: true, message: "请输入交易地址", trigger: "blur" }
    ],
    md_address: [
      { required: true, message: "请输入行情地址", trigger: "blur" }
    ],
    app_id: [{ required: true, message: "请输入AppID", trigger: "blur" }],
    auth_code: [{ required: true, message: "请输入授权码", trigger: "blur" }],
    broker_name_cn: [
      { required: false, message: "请输入期货公司名称", trigger: "blur" }
    ]
  });

  const formColumns = ref<PlusColumn[]>([
    { label: "配置ID", prop: "name" },
    { label: "配置名称", prop: "name_cn" },
    { label: "用户ID", prop: "user_id" },
    {
      label: "密码",
      prop: "password",
      fieldProps: { type: "password", showPassword: true } as any
    },
    { label: "AppID", prop: "app_id" },
    { label: "授权码", prop: "auth_code" },
    { label: "交易地址", prop: "td_address" },
    { label: "行情地址", prop: "md_address" },
    { label: "BrokerID", prop: "broker_id" },
    { label: "期货公司", prop: "broker_name_cn" }
  ]);

  const dialogModel = ref<CtpSettings>(emptyModel());

  const dialogFormProps = computed(() => ({
    columns: formColumns.value,
    rules: formRules.value,
    labelWidth: "100px",
    clearable: true,
    colProps: { span: isMdUp() ? 12 : 24 },
    rowProps: { gutter: 20 }
  }));

  const openNew = () => {
    dialogMode.value = "new";
    dialogModel.value = emptyModel();
    dialogVisible.value = true;
  };

  const openEdit = () => {
    if (!currentRow.value) return;
    dialogMode.value = "edit";
    dialogModel.value = { ...(currentRow.value as CtpSettings) };
    dialogVisible.value = true;
  };

  const openCopy = () => {
    if (!currentRow.value) return;
    dialogMode.value = "copy";
    const copy = { ...(currentRow.value as CtpSettings) };
    copy.name = "";
    dialogModel.value = copy;
    dialogVisible.value = true;
  };

  const closeDialog = () => {
    dialogVisible.value = false;
  };

  const handleConfirm = async (values: any) => {
    try {
      const payload = values as CtpSettings;
      if (dialogMode.value === "edit") {
        await updateCtpSettings(payload);
        message("配置更新成功", { type: "success" });
      } else {
        await createCtpSettings(payload);
        message("配置创建成功", { type: "success" });
      }
      closeDialog();
      await fetchAll();
    } catch (err) {
      message(`提交配置失败: ${err}`, { type: "error" });
    }
  };

  const handleConfirmError = () => {
    message("请填写所有必填字段", { type: "warning" });
  };

  const fetchAll = async () => {
    try {
      const res = await getAllCtpSettings();
      tableData.value = (res as any)?.data || [];
    } catch (e) {
      message(`Failed to fetch CTP settings: ${e}`, { type: "error" });
    }
  };

  onMounted(fetchAll);

  return {
    // header
    searchQuery,
    openNew,
    openEdit,
    openCopy,
    isRowSelected,

    // table
    tableColumns,
    tableSize,
    filteredData,
    onCurrentChange,
    onRowClick,

    // dialog/form
    dialogVisible,
    dialogProps,
    dialogFormProps,
    dialogModel,
    handleConfirm,
    handleConfirmError,
    closeDialog
  };
}
